﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using Microsoft.Office.Interop.Excel;
using myOffice = Microsoft.Office.Interop.Word;
using TecData.Manager;
using TecContracts;
using TecBaseObjects;
using System.Xml;
using System.Xml.Linq;

namespace TecTools {

    public class Tools {

        #region Members

        private const string errType = "Err";
        private const string logType = "Log";
        private const string logArea = "TpTools.Tools";

        enum PersonTitel : int {
            DDr = 1,
            DiplIng = 2,
            Dkfm = 3,
            Dr = 4,
            Ing = 5,
            Mag = 6,
            MMag = 7
        }

        public enum tpCopyType {
            JobEvidenz = 1,
            Leistungen = 2,
            Kalkulation = 3
        }

        public enum tpContent {
            AllJobs = 1,
            ProjectJobs = 2,
            InternJobs = 3
        }

        public enum tpSorting {
            Date = 1,
            Area = 2,
            Hour = 3
        }

        public enum tpSortOrder {
            Up = 1,
            Down = 2
        }

        public enum tpShow {
            Area = 1,
            List = 3
        }

        #region Feiertage

        private static List<DateTime> Feiertage = new List<DateTime> { new DateTime(2012, 1, 1), 
		  new DateTime(2012, 1, 6), 
		  new DateTime(2012, 4, 9), 
		  new DateTime(2012, 5, 1),
		  new DateTime(2012,5,17),
		  new DateTime(2012,5,28), 
		  new DateTime(2012,6,7), 
		  new DateTime(2012,8,15), 
		  new DateTime(2012,10,26), 
		  new DateTime(2012,11,1), 
		  new DateTime(2012,12,8), 
		  new DateTime(2012,12,25), 
		  new DateTime(2012,12,26), 
		  new DateTime(2013,1,1), 
		  new DateTime(2013,1,6), 
		  new DateTime(2013,4,1), 
		  new DateTime(2013,5,1), 
		  new DateTime(2013,5,9), 
		  new DateTime(2013,5,20), 
		  new DateTime(2013,5,30), 
		  new DateTime(2013,8,15), 
		  new DateTime(2013,10,26), 
		  new DateTime(2013,11,1), 
		  new DateTime(2013,12,8), 
		  new DateTime(2013,12,25), 
		  new DateTime(2013,12,26),
          new DateTime(2014,1,1),
          new DateTime(2014,1,6),
          new DateTime(2014,4,21),
          new DateTime(2014,5,1),
          new DateTime(2014,5,29),
          new DateTime(2014,6,9),
          new DateTime(2014,6,19),
          new DateTime(2014,8,15),
          new DateTime(2014,10,26),
          new DateTime(2014,11,1),
          new DateTime(2014,12,08),
          new DateTime(2014,12,25),
          new DateTime(2014,12,26),
          new DateTime(2015,1,1),
          new DateTime(2015,1,6),
          new DateTime(2015,4,6),
          new DateTime(2015,5,1),
          new DateTime(2015,5,14),
          new DateTime(2015,5,25),
          new DateTime(2015,6,4),
          new DateTime(2015,8,15),
          new DateTime(2015,10,26),
          new DateTime(2015,11,1),
          new DateTime(2015,12,08),
          new DateTime(2015,12,25),
          new DateTime(2015,12,26)
	  };

        #endregion
        
        #endregion

        #region Constructor
        #endregion

        #region Properties
        #endregion

        #region Methods
        
        public static void RepairJEHyperlinks(Microsoft.Office.Interop.Excel.Application exApp, Workbook wb, Worksheet sh) {

            int startZeile = 3;
            bool weiter = false;
            try {
                while (weiter == false) {
                    Range c1 = sh.Cells[startZeile, "BB"];
                    Range r1 = sh.Cells[startZeile, "B"];
                    if (r1.Value != null) {
                        if (r1.Value.ToString().Contains("Summe")) {
                            return;
                        }
                    }
                    if (c1.Value != null) {
                        Range c2 = sh.Cells[startZeile, "C"];
                        if (c2.Hyperlinks.Count > 0) {
                            c2.Hyperlinks.Delete();
                        }
                        c2.Hyperlinks.Add(c2, c1.Value.ToString(), Path.GetFileNameWithoutExtension(c1.Value.ToString()));
                    }
                    startZeile++;
                }
            } catch (Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "RepairJEHyperlinks: " + ex.Message, true);
            }
        }

        public static void SendMail(string from, string to, string subject, string msg, object att) {

            try {
                SmtpClient mail = new SmtpClient("tp-s01");
                mail.DeliveryMethod = SmtpDeliveryMethod.Network;
                //mail.Credentials = new NetworkCredential("Es", "Epson1@tp");
                mail.UseDefaultCredentials = true;
                mail.EnableSsl = false;
                mail.Send(from, to, subject, msg);



            } catch(Exception ex) {
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "SendMail: " + ex.Message, true);
            }
        }

        public static string SaveAsPDF(myOffice.Document mDoc) {
            object fileFormat = myOffice.WdSaveFormat.wdFormatPDF;
            object oMissing = System.Reflection.Missing.Value;
            string fileName = "";
            try {
                fileName = mDoc.FullName.Replace(".docx", ".pdf");
                if(File.Exists(fileName)) {
                    File.Delete(fileName);
                }
                mDoc.SaveAs2(fileName, fileFormat);
                return fileName;
            } catch(Exception ex) {
                fileName = "";
                LogDataManager.SaveLog(Contracts.MyUser.UserID, errType, logArea, "SaveAsPDF: " + ex.Message, true);
            }
            return fileName;
        }

        #endregion

        #region Functions

        public static bool ExistsContentInColumn(Worksheet sh, string column, object value) {
            Range col1 = sh.Columns[column];
            Range erg = col1.Find(value);
            return erg != null;
        }

        public static bool FileIsInUse(string fileName) {
            try {
                using(Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Write)) {
                }
                return false;
            } catch {
                return true;
            }
        }

        public static double GetDistance(string startAddress, string targetAddress) {
            double ret = 0.0;
            string url = @"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=" +
                        startAddress + "&destinations=" + targetAddress +
                        "&mode=driving&sensor=false&language=en-EN&units=metric";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader sreader = new StreamReader(dataStream);
            string responsereader = sreader.ReadToEnd();
            response.Close();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(responsereader);
            if (xmldoc.GetElementsByTagName("status")[0].ChildNodes[0].InnerText == "OK") {
                XmlNodeList distance = xmldoc.GetElementsByTagName("distance");
                string km = distance[0].ChildNodes[1].InnerText.Replace(" km", "");
                ret = Convert.ToDouble(km.Replace(".", ","));
            }
            return ret;
        }

        public static DateTime GetFirstDayOfMonth(DateTime dateTime) {
            return new DateTime(dateTime.Year, dateTime.Month, 1);
        }

        public static DateTime GetFirstDayOfWeek(DateTime dateTime) {
            while(dateTime.DayOfWeek != DayOfWeek.Monday)
                dateTime = dateTime.Subtract(new TimeSpan(1, 0, 0, 0));
            return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
        }

        public static DateTime GetLastDayOfMonth(DateTime dateTime) {
            DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
            return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
        }

        public static DateTime GetLastDayOfWeek(DateTime dateTime) {
            while(dateTime.DayOfWeek != DayOfWeek.Sunday)
                dateTime = dateTime.AddDays(1);
            return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day);
        }

        public static DateTime GetLastDayOfYear(DateTime dateTime) {
            DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, 12, 31);
            return firstDayOfTheMonth;
        }

        public static DateTime GetNextDueDate(DateTime nowDate) {
            return GetNextDueDate(nowDate, 14);
        }

        public static DateTime GetNextDueDate(DateTime nowDate, int plusDays) {
            DateTime ret = nowDate;
            if (nowDate.DayOfWeek == DayOfWeek.Tuesday) {
                ret = nowDate.AddDays(-1);
            }
            if (nowDate.DayOfWeek == DayOfWeek.Wednesday) {
                ret = nowDate.AddDays(-2);
            }
            if (nowDate.DayOfWeek == DayOfWeek.Thursday) {
                ret = nowDate.AddDays(-3);
            }
            if (nowDate.DayOfWeek == DayOfWeek.Friday) {
                ret = nowDate.AddDays(-4);
            }
            if (nowDate.DayOfWeek == DayOfWeek.Saturday) {
                ret = nowDate.AddDays(-5);
            }
            if (nowDate.DayOfWeek == DayOfWeek.Sunday) {
                ret = nowDate.AddDays(-6);
            }
            ret = ret.AddDays(plusDays);
            return ret;
        }

        public static string GetPersonenTitel(int titelID) {
            string ret = "";
            switch (titelID) {
                    case (int)PersonTitel.DDr:
                        ret = "DDr.";
                        break;
                    case (int)PersonTitel.DiplIng:
                        ret = "Dipl.Ing.";
                        break;
                    case (int)PersonTitel.Dkfm:
                        ret = "Dkfm.";
                        break;
                    case (int)PersonTitel.Dr:
                        ret = "Dr.";
                        break;
                    case (int)PersonTitel.Ing:
                        ret = "Ing.";
                        break;
                    case (int)PersonTitel.Mag:
                        ret = "Mag.";
                        break;
                    case (int)PersonTitel.MMag:
                        ret = "MMag.";
                        break;
                    default:
                        break;
                }
           
            return ret;
        }

        public static string GetRechtsform(int rf) {
            string ret = "";
            switch (rf) {
                case 3:
                    ret = "& Co";
                    break;
                case 5:
                    ret = "GenmbH";
                    break;
                case 6:
                    ret = "GmbH";
                    break;
                case 7:
                    ret = "GmbH & Co KG";
                    break;
                case 8:
                    ret = "KG";
                    break;
                case 9:
                    ret = "OHG";
                    break;
                case 10:
                    ret = "OEG";
                    break;
                case 11:
                    ret = "A/S";
                    break;
                case 12:
                    ret = "K.V.";
                    break;
                case 13:
                    ret = "& Co GmbH";
                    break;
                case 14:
                    ret = "GmbH & Co";
                    break;
                case 15:
                    ret = "& Co KG";
                    break;
                case 16:
                    ret = "mbH";
                    break;
                case 17:
                    ret = "mbh & Co KG";
                    break;
                case 18:
                    ret = "B.V.";
                    break;
                case 19:
                    ret = "AG";
                    break;
                case 20:
                    ret = "KEG";
                    break;
                case 21:
                    ret = "GesnbR";
                    break;
                case 22:
                    ret = "AG & Co";
                    break;
                case 23:
                    ret = "AG & Co KG";
                    break;
                case 24:
                    ret = "mbh & Co OHG";
                    break;
                case 25:
                    ret = "GmbH & Co KEG";
                    break;
                case 26:
                    ret = "OG";
                    break;
            }
            return ret;
        }

        public static string GetTpDateToday() {
            return DateTime.Today.Year.ToString() + "-" + DateTime.Today.Month.ToString("00") + "-" + DateTime.Today.Day.ToString("00");
        }

        public static bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle) {
            Double result;
            return Double.TryParse(val, NumberStyle,
                System.Globalization.CultureInfo.CurrentCulture, out result);
        }

        public static string Left(string text, int length) {
            if(length < 0)
                throw new ArgumentOutOfRangeException("length", length, "length must be > 0");
            else if(length == 0 || text.Length == 0)
                return "";
            else if(text.Length <= length)
                return text;
            else
                return text.Substring(0, length);
        }

        public static string Mid(string param, int startIndex, int length) {
            //start at the specified index in the string ang get N number of
            //characters depending on the lenght and assign it to a variable
            string result = param.Substring(startIndex, length);
            //return the result of the operation
            return result;
        }

        public static string Mid(string param, int startIndex) {
            //start at the specified index and return all characters after it
            //and assign it to a variable
            string result = param.Substring(startIndex);
            //return the result of the operation
            return result;
        }

        public static bool MoveFiles(string sourcePath, string targetPath, string seachPattern) {
            bool ret = true;
            try {
                string[] files = Directory.GetFiles(sourcePath, seachPattern);
                string targetFile = "";
                foreach (string file in files) {
                    targetFile = file.Replace(sourcePath, targetPath);
                    File.Move(file, targetFile);
                }
            } catch {
                ret = false;
            }
            return ret;
        }

        public static DateTime NextGoodBusinessDay(DateTime currentDay) {
            DateTime retDay = currentDay.Date.AddDays(1);
            if(retDay.DayOfWeek == DayOfWeek.Saturday) {
                retDay = currentDay.AddDays(3);
            }
            if(retDay.DayOfWeek == DayOfWeek.Sunday) {
                retDay = currentDay.AddDays(2);
            }
            foreach(DateTime ft in Feiertage) {
                if(retDay == ft) {
                    retDay = retDay.AddDays(1);
                }
            }
            foreach(DateTime ft in Feiertage) {
                if(retDay == ft) {
                    retDay = retDay.AddDays(1);
                }
            }
            return retDay;
        }

        public static DateTime NextGoodMonday(DateTime currentDay) {
            DateTime ret = new DateTime(1900, 1, 1);

            if (currentDay.DayOfWeek == DayOfWeek.Monday) {
                ret = currentDay.AddDays(7);
            }
            if (currentDay.DayOfWeek == DayOfWeek.Tuesday) {
                ret = currentDay.AddDays(13);
            }
            if (currentDay.DayOfWeek == DayOfWeek.Wednesday) {
                ret = currentDay.AddDays(12);
            }
            if (currentDay.DayOfWeek == DayOfWeek.Thursday) {
                ret = currentDay.AddDays(11);
            }
            if (currentDay.DayOfWeek == DayOfWeek.Friday) {
                ret = currentDay.AddDays(10);
            }
            if (currentDay.DayOfWeek == DayOfWeek.Saturday) {
                ret = currentDay.AddDays(9);
            }
            if (currentDay.DayOfWeek == DayOfWeek.Sunday) {
                ret = currentDay.AddDays(8);
            }
            return ret;
        }

        public static uint RGB(byte byRed, byte byGreen, byte byBlue) {
            uint res = byBlue;
            res = res << 8;
            res += byGreen;
            res = res << 8;
            res += byRed;
            return res;
        }

        public static T Nz<T>(T Value, T Replacement) {

            try {
                if(Value != null) {
                    if(Value.GetType() != Replacement.GetType()) {
                        if(Replacement.GetType().ToString().Contains("String")) {
                            object ret = Value.ToString();
                            return (T)ret;
                        }
                    }
                    return Value;
                } else {
                    return Replacement;
                }
            } catch(Exception e) {
                Debug.Print(e.ToString());
                return Replacement;
            }

        }

        public static string Right(string original, int numberCharacters) {
            return original.Substring(numberCharacters > original.Length ? 0 : original.Length - numberCharacters);
        }

        public static bool SheetsExists(Workbook wb, string sheetName) {
            foreach(Worksheet s in wb.Sheets) {
                if(s.Name == sheetName) {
                    return true;
                }
            }
            return false;
        }

        #endregion

    }

}
